const API_BASE_URL = 'http://localhost:3001/api';

// 存储token
let authToken: string | null = null;

export const setAuthToken = (token: string) => {
  authToken = token;
  localStorage.setItem('authToken', token);
};

export const getAuthToken = (): string | null => {
  if (!authToken) {
    authToken = localStorage.getItem('authToken');
  }
  return authToken;
};

export const clearAuthToken = () => {
  authToken = null;
  localStorage.removeItem('authToken');
};

// 通用请求函数
const request = async (endpoint: string, options: RequestInit = {}) => {
  const token = getAuthToken();
  const config: RequestInit = {
    headers: {
      'Content-Type': 'application/json',
      ...(token && { Authorization: `Bearer ${token}` }),
      ...options.headers,
    },
    ...options,
  };

  const response = await fetch(`${API_BASE_URL}${endpoint}`, config);
  
  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}));
    throw new Error(errorData.error || `HTTP error! status: ${response.status}`);
  }
  
  return response.json();
};

// 用户认证API
export const authAPI = {
  login: async (username: string, password: string) => {
    return request('/login', {
      method: 'POST',
      body: JSON.stringify({ username, password }),
    });
  },

  register: async (username: string, email: string, password: string) => {
    return request('/register', {
      method: 'POST',
      body: JSON.stringify({ username, email, password }),
    });
  },
};

// 食物API
export const foodAPI = {
  getFoods: async (search?: string) => {
    const params = search ? `?search=${encodeURIComponent(search)}` : '';
    return request(`/foods${params}`);
  },

  getFoodById: async (id: string) => {
    return request(`/foods/${id}`);
  },
};

// 记录API
export const recordAPI = {
  getRecords: async (date?: string) => {
    const params = date ? `?date=${date}` : '';
    return request(`/records${params}`);
  },

  addRecord: async (data: {
    food_id: number;
    portion_value: number;
    portion_unit?: string;
    record_date: string;
    meal_type?: string;
  }) => {
    return request('/records', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  },

  deleteRecord: async (id: number) => {
    return request(`/records/${id}`, {
      method: 'DELETE',
    });
  },
};

// 历史记录API
export const historyAPI = {
  getHistory: async (page: number = 1, limit: number = 10) => {
    return request(`/history?page=${page}&limit=${limit}`);
  },

  deleteRecord: async (id: string) => {
    return request(`/history/${id}`, {
      method: 'DELETE',
    });
  },
};

// 用户API
export const userAPI = {
  getProfile: async () => {
    return request('/user/profile');
  },

  updateProfile: async (data: {
    nickname?: string;
    gender?: string;
    age?: number;
    height?: number;
    weight?: number;
    daily_calorie_target?: number;
  }) => {
    return request('/user/profile', {
      method: 'PUT',
      body: JSON.stringify(data),
    });
  },
};